package com.jzo2o.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.mapper.ActivityMapper;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.dto.request.ActivityQueryForPageReqDTO;
import com.jzo2o.market.model.dto.request.ActivitySaveReqDTO;
import com.jzo2o.market.model.dto.response.ActivityInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {
    private static final int MILLION = 1000000;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ICouponService couponService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;


    /**
     * 新增优惠券活动
     *
     * @param dto
     */
    @Override
    public void saveCouponActivity(ActivitySaveReqDTO dto) {
        //1.调用检查方法
        dto.check();

        Activity activity = BeanUtils.copyBean(dto, Activity.class);
        activity.setStatus(ActivityStatusEnum.NO_DISTRIBUTE.getStatus());
        //2.判断是否有主键id
        if (dto.getId() == null) {
            //3.直接新增即可
            boolean result = save(activity);
            if (!result) {
                throw new DBException("新增优惠券活动失败");
            }
        } else {
            //4.执行更新操作
            boolean result = updateById(activity);
            if (!result) {
                throw new DBException("新增优惠券活动失败");
            }
        }

    }

    /**
     * 查询优惠券列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<ActivityInfoResDTO> pageList(ActivityQueryForPageReqDTO dto) {
        //1.构建分页请求条件
        LambdaQueryWrapper<Activity> queryWrapper = Wrappers.<Activity>lambdaQuery()
                .eq(dto.getStatus() != null, Activity::getStatus, dto.getStatus())
                .eq(dto.getType() != null, Activity::getType, dto.getType())
                .like(dto.getName() != null && !dto.getName().equals(""), Activity::getName, dto.getName())
                .eq(dto.getId() != null, Activity::getId, dto.getId());
        //2.查询列表
        List<Activity> activityList = this.list(queryWrapper);
        //3.封装数据
        List<ActivityInfoResDTO> activityInfoResDTOS = BeanUtils.copyToList(activityList, ActivityInfoResDTO.class);
        return PageHelperUtils.selectPage(dto, () -> activityInfoResDTOS);
    }

    /**
     * 查询优惠券详情
     *
     * @param id
     * @return
     */
    @Override
    public ActivityInfoResDTO getActivityById(Long id) {
        return BeanUtils.copyBean(getById(id), ActivityInfoResDTO.class);
    }


    /**
     * 撤销优惠券活动
     *
     * @param id
     */
    @Override
    @Transactional
    public void revoke(Long id) {
        //1.根据优惠券活动id查询优惠券活动
        Activity activity = this.getById(id);
        if (activity == null) {
            throw new BadRequestException("没有此优惠券活动");
        }
        //2.将状态是 待生效 进行中 的券改为作废
        List<Integer> activityStatusList = Arrays.asList(ActivityStatusEnum.NO_DISTRIBUTE.getStatus(), ActivityStatusEnum.DISTRIBUTING.getStatus());
        if (!activityStatusList.contains(activity.getStatus())) {
            throw new BadRequestException("不是待生效,进行中的状态,不能撤销");
        }
        boolean result = this.lambdaUpdate().eq(Activity::getId, activity.getId())
                .set(Activity::getStatus, CouponStatusEnum.VOIDED.getStatus())
                .update();
        if (!result) {
            throw new DBException("更新状态失败");
        }
        //3.同时查询 优惠券领取记录表 将 未使用的券 作废
        List<Coupon> couponList = couponService.lambdaQuery().eq(Coupon::getActivityId, id).list();
        if (CollUtils.isNotEmpty(couponList)) {
            couponList.stream().filter(coupon -> coupon.getStatus().equals(CouponStatusEnum.NO_USE.getStatus())).forEach(
                    x -> couponService.lambdaUpdate().eq(Coupon::getId, x.getId()).set(Coupon::getStatus, CouponStatusEnum.INVALID.getStatus()).update()
            );
        }
    }
}
